package omm.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import omm.domain.Quotation;
import omm.domain.Quotation.State;
import omm.domain.evolutiongraph.EvolutionGraphic;
import omm.domain.generalgraph.MonetaryGraphic;
import omm.domain.generalgraph.QuantityGraphic;
import omm.services.QuotationServices;
import omm.util.Graphics;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class QuotationController /*extends HttpServlet*/ {

	private QuotationServices quotationServices;

	@Autowired
	public QuotationController(QuotationServices quotationServices) {
		this.quotationServices = quotationServices;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView allQuotations() {
		ModelAndView mav = new ModelAndView();
		// mav.addObject("quotationsSize",
		// quotationServices.getBusinessFilterQuotations().size());
		return mav;
	}
	
	private DateTime calculateEnding(DateTime now){
		DateTime aux = now.minusMonths(1);
		return new DateTime(now.getYear(),aux.getMonthOfYear(),aux.dayOfMonth().withMaximumValue().getDayOfMonth(),23,59,59);
	}

	@RequestMapping(method = RequestMethod.POST)
	public void showGeneralViewGraphics(HttpServletResponse response) throws IOException {
		DateTime now = DateTime.now();
		DateTime beginning = new DateTime(now.getYear(),1,1,0,0,0);//now.getYear()
		DateTime ending = new DateTime(now.getYear(),12,31,23,59,59);
	
		List<Quotation> quotations = quotationServices.getBusinessFilterQuotations(beginning, ending);

		MonetaryGraphic monetary = quotationServices.getMonetaryGraphic(quotations, beginning, ending);
		String monetaryURL = monetary.getGraphicURL();
		Map<State, Double> mapmonetary = monetary.getCommisionDataMap();

		///////*******************En miles************************************///////
		Long mquoted =  ((Math.round(mapmonetary.get(State.QUOTED) * 100)) / 100) /1000;
		Long mlost =  ((Math.round(mapmonetary.get(State.LOST) * 100)) / 100) / 1000;
		Long mwon =  ((Math.round(mapmonetary.get(State.WON) * 100)) / 100) / 1000;
		///////****************************************************************///////

		QuantityGraphic quantity = quotationServices.getQuantityGraphic(quotations, beginning, ending);
		String quantityURL = quantity.getGraphicURL();
		Map<Quotation.State, Integer> mapquantity = quantity.getCommisionDataMap();

		Integer qquoted = mapquantity.get(State.QUOTED);
		Integer qlost = mapquantity.get(State.LOST);
		Integer qwon = mapquantity.get(State.WON);
		
		PrintWriter out = response.getWriter();
		
		out.print("<html><body>" + "<div class=\"centrar\" style= \"width: 430px;\">" +
				"<div id=\"monetary\" class=\"generalviewgraph\" style= \"height: 200px;width: 430px;padding-bottom: 60px;padding-top: 40px;\">" +
				"<img src=\""+ monetaryURL + "\" alt = \"Su browser no soporta imagenes\"/>" +
			"</div>" +
			"<div id=\"quantity\" class=\"generalviewgraph\" style = \"height: 200px;width: 430px;padding-bottom: 60px;\">"+
				"<img src=\""+ quantityURL + "\" alt = \"Su browser no soporta imagenes\"/>" +
			"</div>" +
			"<table align=\"center\" style=\"width:430px; line-height: 30px; margin:auto;width:100%;zoom:1;overflow:hidden;font-size: 24px;font-family:\"Arial\";\">" 
			+ "<tbody><tr style=\"background:#8b0027;color:white;padding:3px;\" ><th >Comisiones</th><th>Miles $</th><th>Cant. Empresas</th></tr>" 
			+		"<tr style=\"background:#e5e5ef;\"><td style=\"text-align:center;\">Pendiente</td>" 
			+		"<td style=\"text-align:center;\">" + mquoted.toString() + "</td>" 
			+		"<td style=\"text-align:center;\">" + qquoted.toString() + "</td></tr>" 
			+		"<tr style=\"background:#eaf4f8 !important;\"><td style=\"text-align:center;\">Ganada</td>" 
			+		"<td style=\"text-align:center;\">"+ mwon.toString() +"</td>" 
			+		"<td style=\"text-align:center;\">"+ qwon.toString() +"</td></tr>" 
			+		"<tr style=\"background:#e5e5ef;\" class=\"odd\"><td style=\"text-align:center;\">Perdida</td>" 
			+		"<td style=\"text-align:center;\">" +mlost.toString()+ "</td>" 
			+		"<td style=\"text-align:center;\">" + qlost.toString() + "</td></tr>" 
			+		"</tbody></table>"
			+"</div>" +"</body></html>");
		out.close();
		
/* Si se quiere volver a usar los .jsp TENER CUIDADO CON 3G!!!!!! */
/* Se supone que el problema puede ser el content-type */
//		 mav.addObject("monetary", monetaryURL);
//		 mav.addObject("mquoted", (double) (Math.round(mapmonetary.get(State.QUOTED) * 100)) / 100);
//		 mav.addObject("mlost", (double) (Math.round(mapmonetary.get(State.LOST) * 100)) / 100);
//		 mav.addObject("mwon", (double) (Math.round(mapmonetary.get(State.WON) * 100)) / 100);
		
//		 mav.addObject("quantity", quantityURL);		
//		 mav.addObject("qquoted",mapquantity.get(State.QUOTED));
//		 mav.addObject("qlost",mapquantity.get(State.LOST));
//		 mav.addObject("qwon",mapquantity.get(State.WON));
//
//		 mav.addObject("error", '0');		
		
//		return mav;
	}

	@RequestMapping(method = RequestMethod.POST)
	public void showEvolutionViewGraphic(@RequestParam("periodo") String periodStr,
			@RequestParam("comision") String commitionStr, @RequestParam("unidad") String unitStr,HttpServletResponse response) throws IOException{
//		ModelAndView mav = new ModelAndView();

		DateTime now = DateTime.now();
		DateTime ending = calculateEnding(now);
		DateTime beginning = new DateTime(now.getYear() - 1 ,now.getMonthOfYear() ,1,0,0,0);
		
//		TODO: Siempre es ganada, deberia arreglarse la parte de BB para que mande ganada siempre para usar esto:	
//		int commition = (commitionStr.equals("todos")) ? 1 : commitionStr.equals("pendiente") ? 2
//				: commitionStr.equals("ganada") ? 3 : 4;
		int commition = 3; //Siempre ganada
		int unit = (unitStr.equals("miles")) ? 1 : 2;

		List<Quotation> quotations = quotationServices.getBusinessFilterQuotations(beginning, ending);
		
		int closedMonthPeriod = 1;
		EvolutionGraphic evolutionClosedMonth = quotationServices.getEvolutionGraphic(quotations,closedMonthPeriod, commition,
				unit, beginning, ending);
		String evolutionClosedMonthURL = evolutionClosedMonth.getGraphicURL();
		String closedMonthTitle = Graphics.makeTitle("EVOLUCION ", evolutionClosedMonth.getStart(), evolutionClosedMonth.getEnd());
		
		int calendarYearPeriod = 2;
		EvolutionGraphic evolutionCalendarYear = quotationServices.getEvolutionGraphic(quotations,calendarYearPeriod,commition, unit, beginning, ending);
		String evolutionCalendarYearURL = evolutionCalendarYear.getGraphicURL();
		String calendarYearTitle = Graphics.makeTitle("EVOLUCION ", evolutionCalendarYear.getStart(),evolutionCalendarYear.getEnd());

		int lastYearPeriod = 3;// TODO: Ver de ponerlo mas lindo
		EvolutionGraphic evolutionLastYear = quotationServices.getEvolutionGraphic(quotations,lastYearPeriod, commition, unit,
				beginning, ending);
		String evolutionLastYearURL = evolutionLastYear.getGraphicURL();
		String lastYearTitle = Graphics.makeTitle("EVOLUCION ", evolutionLastYear.getStart(),evolutionLastYear.getEnd()); 
		
		PrintWriter out = response.getWriter();
		out.print("<html><body>" +  "<div id = \"evolution\" class = 'container' >" 
				+"<div class=\"title\" style=\"margin-left: 8%; font-family:Arial; font-size:20px;\">"+lastYearTitle+"</div>" 
				+"<div id=\"lastyear\"><img class= 'centrar' src=\"" + evolutionLastYearURL +"\"></div>" 
				+"<div class=\"title\" style=\"margin-top: 10%;margin-left: 8%; font-family:Arial; font-size:20px;\">"+calendarYearTitle+"</div>" 
				+"<div id=\"calendaryear\"><img class= 'centrar' src=\"" + evolutionCalendarYearURL +"\"></div>" 
				+"<div class=\"title\" style=\"margin-top: 10%;margin-left: 8%; font-family:Arial; font-size:20px;\">"+closedMonthTitle+"</div>" 
				+"<div id=\"closedmonth\"><img class= 'centrar' src=\"" + evolutionClosedMonthURL +"\"></div>"
				+"</div>"
				+ "</body></html>");
		
		out.close();
		
/* Si se quiere volver a usar los .jsp TENER CUIDADO CON 3G!!!!!! */
/* Se supone que el problema puede ser el content-type */
//		mav.addObject("evolutionLastYearURL", evolutionLastYearURL);
//		mav.addObject("evolutionCalendarYearURL", evolutionCalendarYearURL);
//		mav.addObject("evolutionClosedMonthURL", evolutionClosedMonthURL);
//
//		mav.addObject("error", '0');
//
//		return mav;
	}
	
	@Deprecated //Desactualizado si se quiere reimplementar se debera ajustar a 3g
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView showComparisonViewGraphic(@RequestParam("agrupacion") String groupStr,
			@RequestParam("comision") String commitionStr, @RequestParam("grafico") String graphicStr) {
		ModelAndView mav = new ModelAndView();

		int groupby = (groupStr.equals("producto")) ? 1 : 2;
		int commission = (commitionStr.equals("todos")) ? 1 : commitionStr.equals("pendiente") ? 2
				: commitionStr.equals("ganada") ? 3 : 4;
		int graphic = (graphicStr.equals("torta")) ? 1 : 2;

		String evolutionURL = quotationServices.getComparativeGraphic(groupby, commission, graphic);
		mav.addObject("comparatives", evolutionURL);
		mav.addObject("error", '0');

		return mav;
	}
}
